<template>
  <basic-container>
    <avue-crud v-show="!exemptToggle" :option="option" v-model:search="search" v-model:page="page" v-model="form" :data="data"
               :permission="permissionList" :before-open="beforeOpen" ref="crud" @row-update="rowUpdate"
               @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
               @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
               @refresh-change="refreshChange" @on-load="onLoad" >
      <template #menu="{row}">
        <el-button type="primary" link plain @click="publishHandle(row)">发布</el-button>
        <el-button type="primary" link plain @click="unPublishHandle(row)">取消发布</el-button>
        <el-button type="primary" link plain @click="exempt(row.id)">免考设置</el-button>
      </template>
    </avue-crud>
    <cer-exempt v-if="exemptToggle" :certificateId="certificateId" @back="()=>{ exemptToggle = false }"></cer-exempt>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, unPublish, publish } from '@/api/position/certificate';
import option from '@/option/position/certificate';
import { mapGetters } from 'vuex';
import { exportBlob } from '@/api/common';
import { getToken } from '@/utils/auth';
import { downloadXls } from '@/utils/util';
import { dateNow } from '@/utils/date';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import CerExempt from '@/views/position/cerExempt.vue';

export default {
  components: { CerExempt },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: option,
      data: [],
      //操作的证书
      certificateId:'',
      //免考设置开关
      exemptToggle:false,
      //证书分类id
      categoryId:''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.validData(this.permission.certificate_add, false),
        viewBtn: this.validData(this.permission.certificate_view, false),
        delBtn: this.validData(this.permission.certificate_delete, false),
        editBtn: this.validData(this.permission.certificate_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  methods: {
    /**
     * 改变证书分类
     * @param id
     */
    categoryChange(id){
      this.categoryId= id;
      this.exemptToggle=false
      this.onLoad(this.page);
    },
    exempt(id){
      this.certificateId= id
      this.exemptToggle=true
    },
    publishHandle(row) {
      publish(row.id).then(res => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '发布成功!'
        });
      });
    },
    unPublishHandle(row) {
      unPublish(row.id).then(res => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '取消成功!'
        });
      });
    },
    rowSave(row, done) {
      row.classificationId = this.categoryId
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
        done();
      }, error => {
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    handleExport() {
      let downloadUrl = `/position/certificate/export-certificate?${this.website.tokenHeader}=${getToken()}`;
      const {
        organization,
        type,
        name,
        note
      } = this.query;
      let values = {
        organization_like: organization,
        type_equal: type,
        name_like: name,
        note_like: note
      };
      this.$confirm('是否导出数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        NProgress.start();
        exportBlob(downloadUrl, values).then(res => {
          downloadXls(res.data, `证书${dateNow()}.xlsx`);
          NProgress.done();
        });
      });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page) {
      if (!this.categoryId) {
        return;
      }
      //证书分类 classificationId
      // this.query.id = this.forms.id

      getList(page.currentPage, page.pageSize, { ...this.query, classificationId: this.categoryId }).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.selectionClear();
      });
    }
  }
};
</script>

<style></style>
